package com.tan00xu.myAnnotation.log;

import com.alibaba.fastjson.JSON;
import com.tan00xu.utils.HttpContextUtils;
import com.tan00xu.utils.IpUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.joda.time.DateTime;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;

@Component
@Aspect
@Slf4j
public class LogAspect {
    @Pointcut("@annotation(com.tan00xu.myAnnotation.log.LogAnnotation)")
    public void logPointCut() {
    }

    //环绕通知
    @Around("logPointCut()")
    public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable {
        long beginTime = System.currentTimeMillis();
        //执行方法
        Object result = joinPoint.proceed();
        //执行时长(毫秒)
        long endTime= System.currentTimeMillis();
        //保存日志
        recordLog(joinPoint,beginTime,endTime, beginTime-endTime);
        return result;
    }

    private void recordLog(ProceedingJoinPoint joinPoint,long beginTime,long endTime, long time) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        //得到方法上的注解
        LogAnnotation logAnnotation = method.getAnnotation(LogAnnotation.class);
        log.info("=====================log start================================");
        log.info("开始时间：{}",new DateTime(beginTime).toString("yyyy-MM-dd HH:mm:ss"));
        log.info("结束时间：{}",new DateTime(endTime).toString("yyyy-MM-dd HH:mm:ss"));
        log.info("module:{}",logAnnotation.module());
        log.info("operation:{}",logAnnotation.operation());
        //请求的方法名
        String className = joinPoint.getTarget().getClass().getName();
        String methodName = signature.getName();
        log.info("request method:{}",className + "." + methodName + "()");

//        //请求的参数
        Object[] args = joinPoint.getArgs();
        String params = JSON.toJSONString(args[0]);
        log.info("params:{}",params);

        //获取request 设置IP地址
        HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
        log.info("ip:{}", IpUtils.getIpAddress(request));
//        SimpleDateFormat simpleDateFormat = new SimpleDateFormat();
//        simpleDateFormat.format()

        log.info("execute time : {} ms",time);
        log.info("=====================log end================================");
    }

}
